package indi.mozping.threadpool.invokeany;

import indi.mozping.tools.SleepTools;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author by mozping
 * @Classname InvokeAllTest
 * @Description TODO
 * @Date 2019/10/19 10:08
 */
public class InvokeAnyTimedTest {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        List<Callable<String>> list = new ArrayList<>();
        for (int i = 1; i < 10; i++) {
            list.add(new MyTask(i + ""));
        }
        String result = null;
        try {
            result = executorService.invokeAny(list, 300, TimeUnit.MILLISECONDS);
        } catch (TimeoutException e) {
            System.err.println(e.getClass());
            e.printStackTrace();
        }
        System.out.println(result);
        executorService.shutdown();
    }

    static class MyTask implements Callable<String> {

        String id;

        public MyTask(String id) {
            this.id = id;
        }

        @Override
        public String call() throws Exception {
            long begin = System.currentTimeMillis();
            SleepTools.randomMs(5000);
            return id + " -- " + (System.currentTimeMillis() - begin);
        }
    }

}